/**************************************************************************************** Import */
import _ from 'lodash';
import React, {Component} from 'react';
import { View, TextInput, Linking, Text } from 'react-native';
import { Icon,  List, Button, InputItem, Tabs, TextareaItem, Modal } from 'antd-mobile-rn';
import Picker from 'react-native-picker';
import { CAround, CBetween, CCenter, CColumn, CFloat, CHand, CItemX, CItemY, CLine, CLoad, CRow, CWrap, CBone, CIcon, CImage, CSvg, CText, CFull, CScroll, CFooter, CHeader, CPage, CButton, CLabel, PTabbar, PHeader } from '../../../library/comp';
import { Dialog, Http, PageBase } from '../../../library/func';
import Design from '../../../design';
import Config from '../../../config';
import ImagePicker from 'react-native-image-crop-picker';
//微信集成模块  
import * as WeChat from 'react-native-wechat';

// import { TextInput, ScrollView } from 'react-native-gesture-handler';

/**************************************************************************************** Pageload */

/**************************************************************************************** Cacheload */

/**************************************************************************************** Preload */

/**************************************************************************************** Get */

/**************************************************************************************** Post */

/**************************************************************************************** Page */
export default class Pay extends PageBase {
	constructor(props) {
        super(props);
 		this.state = {
            //  报修类型
            type:'月租',
            paymoney:0.01,
            set_number:"",
            errstr:"未获取",
        }
        WeChat.registerApp("wxf4096e80d85bb200");
    }

    /************************************************************************************ Life */
    /**
     * didMount
     */
    componentDidMount(){
        this.setDataFromParams();
    }

    //获取传参赋值
    setDataFromParams = () => {
        let set_number = this.props.navigation.state.params.set_number;
        this.setState({
            set_number : set_number,
        })
    }

    //生成订单 统一下单
    makeOrder = () => {


        WeChat.isWXAppInstalled()
        .then((isInstalled) => 
        {
            if(isInstalled){
                Http.post({
                    url: 'page/outcar/logic/pay.php',
                    data: {
                        set_number:this.state.set_number,
                        set_type:this.state.type,
                        set_pay:this.state.paymoney,
                    },
                    success: (data)=> {
                        console.log('生成订单',data);
                        this.doWechatPay(data.orderid, data.total_fee);
                    },
                    pipe: Config.pipe.action.default
                })        
            }else{
                Dialog.text("请安装微信", 1);
            }
        }
        )

    }


    //统一下单 支付
    doWechatPay = (orderid, total_fee) => {
        let data = "key=heshequ_outcar&orderid=" + orderid + "&total_fee=" + total_fee;
        let url = "https://activepage.sgboke.com/pay/wepay/jsapi2.php";

        fetch(url, {  
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            method: 'post',
            body: data
        }).then((resp) => {

            console.log('支付接口返回',resp)

            let res = JSON.parse(resp._bodyText);  
            res.timeStamp = res.timestamp.toString();    

            let pay_data = {
                partnerId: res.partnerid,  // 商家向财付通申请的商家id
                prepayId: res.prepayid,   // 预支付订单
                nonceStr: res.noncestr,   // 随机串，防重发
                timeStamp: res.timestamp,  // 时间戳，防重发.
                package: res.package,    // 商家根据财付通文档填写的数据和签名
                sign: res.sign       // 商家根据微信开放平台文档对数据做的签名
            };

            WeChat.pay(pay_data).then((requestJson)=>{
                //支付成功回调     
                if (requestJson.errCode=="0"){
                    Dialog.text("支付成功", 1);
                    this.nav.navigate('Service_Cartpark');
                }
            }).catch((err)=>{
                this.setState({
                    errstr:JSON.stringify(err)
                })
                Dialog.text("支付失败", 1);
            })



        });

    }


    /************************************************************************************ Event */


    // 类型
    changeType = (value,money) => {
        this.setState({
            type:value,
            paymoney:money,
        })
    }

    //支付
    pay = () => {
        console.log(this.state.paymoney)
    }


    /************************************************************************************ Render */
	render() {
		return (
			<CPage>
				
				<CScroll mt='96' mb='100' bg='#efeff4'>
                    <CColumn bg='#fff' mt='20' mb='20' px='30' pb='30'>
                        <CText>{ this.state.errstr }</CText>
                        {/* 购买类型 */}
                        <CRow h='80' y='center'>
                            <CText size='26' mr='10'>购买类型</CText>
                        </CRow>
                        <CBetween py='18' bt='1 #eee'>
                            <CHand x='left' f='1'>
                                {
                                    this.state.type == '月租' ? <Text style={[ Design.global.selectButtonActive, {width:95} ]} onPress={e=>{this.changeType('月租')}}>月租</Text> :
                                    <Text style={[ Design.global.selectButtonNormal, {width:95} ]} onPress={e=>{this.changeType('月租', 0.01)}}>月租</Text>
                                }
                            </CHand>
                            <CHand x='center' f='1'>
                                {
                                    this.state.type == '季租' ? <Text style={[ Design.global.selectButtonActive, {width:95} ]} onPress={e=>{this.changeType('季租')}}>季租</Text> :
                                    <Text style={[ Design.global.selectButtonNormal, {width:95} ]} onPress={e=>{this.changeType('季租', 0.02)}}>季租</Text>
                                }
                            </CHand>
                            <CHand x='right' f='1'>
                                {
                                    this.state.type == '年租' ? <Text style={[ Design.global.selectButtonActive, {width:95} ]} onPress={e=>{this.changeType('年租')}}>年租</Text> :
                                    <Text style={[ Design.global.selectButtonNormal, {width:95} ]} onPress={e=>{this.changeType('年租', 0.03)}}>年租</Text>
                                }
                            </CHand>
                        </CBetween>

                    </CColumn>
                    
                    {/* 提交按钮 */}
                    <CColumn py='10' mt='10' px='30'>
                    <CButton  {...Design.global.commonButton} 
                        onPress={e=>{
                           this.makeOrder();
                        }}>支付</CButton>
                    </CColumn>
                    
				</CScroll>

                {/* header */}
				<PHeader nav={this.nav}>充值</PHeader>

			</CPage>
		);
	}
}
